package com.yfree.utils;

import android.app.Activity;
import android.content.Context;
import android.util.Base64;

import com.yfree.YConfig;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class YSerializableUtils {
    public static void save(Activity context, Serializable obj, String key) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(obj);
            context.getSharedPreferences(YConfig.YSHAREDPREFERENCESNAME, Context.MODE_PRIVATE).edit().putString(key, new YDESCrypt(YConfig.localEncryptParamsKey).encrypt(new String(Base64.encode(baos.toByteArray(), Base64.DEFAULT)))).apply();
            oos.flush();
            baos.flush();
            oos.close();
            baos.close();
        } catch (Exception ignored) {
            Object o = null;
        }
    }

    public static Serializable read(Activity context, String key) {
        try {
            ByteArrayInputStream bais = new ByteArrayInputStream(Base64.decode(new YDESCrypt(YConfig.localEncryptParamsKey).decrypt(context.getSharedPreferences(YConfig.YSHAREDPREFERENCESNAME, Context.MODE_PRIVATE).getString(key, "")).getBytes(), Base64.DEFAULT));
            ObjectInputStream bis = new ObjectInputStream(bais);
            Serializable obj = (Serializable) bis.readObject();
            bis.close();
            bais.close();
            return obj;
        } catch (Exception exception) {
            return null;
        }
    }

    public static void delete(Activity context, String key) {
        context.getSharedPreferences(YConfig.YSHAREDPREFERENCESNAME, Context.MODE_PRIVATE).edit().remove(key).apply();
    }
}
